package com.link4a.doms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.link4a.doms.dao.Page;
import com.link4a.doms.dao.handler.DriverHandler;
import com.link4a.doms.dao.handler.ProviderHandler;
import com.link4a.doms.exception.BusinessException;
import com.link4a.doms.exception.ValidationException;
import com.link4a.doms.model.Driver;
import com.link4a.doms.model.Provider;
import com.link4a.doms.vo.ProviderCondition;

@Service
public class ProviderService {
	
	@Autowired
	private ProviderHandler providerHandler;
	@Autowired
	private DriverHandler driverHandler;

	public Provider findById(int id) {
		return providerHandler.findById(id);
	}
	
	public Page<Provider> findPage(ProviderCondition providerCondition) {
		return providerHandler.findPage(providerCondition);
	}
	
	public void create(Provider provider) throws ValidationException, BusinessException {
		if (providerHandler.isNameDuplicated(provider)) {
			throw new ValidationException(ValidationException.DATA_DUPLICATED);
		}

		providerHandler.create(provider);
	}
	
	public void update(Provider provider) throws ValidationException {
		if (providerHandler.isNameDuplicated(provider)) {
			throw new ValidationException(ValidationException.DATA_DUPLICATED);
		}
		
		providerHandler.update(provider);
	}
	
	public void delete(int id) throws BusinessException {
		List<Driver> drivers = driverHandler.findByProvider(id);
		if (drivers != null && !drivers.isEmpty()) {
			throw new BusinessException("存在该供应商的驱动，不允许删除");
		}
		
		providerHandler.delete(id);
	}

	public List<Provider> listByKeyword(String keyword) {
		return providerHandler.listByKeyword(keyword);
	}
}